package com.heima.utils;

import com.aliyun.oss.OSS;
import com.aliyun.oss.OSSClientBuilder;
import com.aliyun.oss.OSSException;
import com.aliyun.oss.common.auth.CredentialsProviderFactory;
import com.aliyun.oss.common.auth.EnvironmentVariableCredentialsProvider;
import com.aliyun.oss.model.PutObjectRequest;
import com.aliyun.oss.model.PutObjectResult;
import com.aliyuncs.exceptions.ClientException;
import com.heima.utils.AliOSSProperties;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Component;
import org.springframework.web.multipart.MultipartFile;

import java.io.IOException;
import java.io.InputStream;
import java.util.UUID;

@Component
public class AliOSSUtils {

    // 注入配置实体类
    @Autowired
    private AliOSSProperties aliOSSProperties;

    // 从本地环境变量中获取AK和AS,再使用之前要确保已经配置过AK&AS
    EnvironmentVariableCredentialsProvider credentialsProvider;

    {
        try {
            credentialsProvider = CredentialsProviderFactory.newEnvironmentVariableCredentialsProvider();
        } catch (ClientException e) {
            throw new RuntimeException(e);
        }
    }

    public String upload(MultipartFile file) throws IOException {

        // 获取地域
        String endpoint = aliOSSProperties.getEndpoint();
        // 获取bucketName
        String bucketName = aliOSSProperties.getBucketName();

        // 创建OSS客户端实例
        OSS oss = new OSSClientBuilder().build(endpoint, credentialsProvider);

        // 避免文件名冲突,以及获取文件的扩展名
        String fileName = UUID.randomUUID() + file.getOriginalFilename().substring(file.getOriginalFilename().indexOf("."));

        try {

            // 获取文件的输入流
            InputStream is = file.getInputStream();

            // 创建上传文件的对象
            PutObjectRequest por = new PutObjectRequest(bucketName, fileName, is);

            // 使用客户端对象创建上传文件的请求,将上传文件对象当做参数传入
            PutObjectResult result = oss.putObject(por);
        } catch (OSSException oe) {
            System.out.println("Caught an OSSException, which means your request made it to OSS, "
                    + "but was rejected with an error response for some reason.");
            System.out.println("Error Message:" + oe.getErrorMessage());
            System.out.println("Error Code:" + oe.getErrorCode());
            System.out.println("Request ID:" + oe.getRequestId());
            System.out.println("Host ID:" + oe.getHostId());
        } catch (com.aliyun.oss.ClientException ce) {
            System.out.println("Caught an ClientException, which means the client encountered "
                    + "a serious internal problem while trying to communicate with OSS, "
                    + "such as not being able to access the network.");
            System.out.println("Error Message:" + ce.getMessage());
        } finally {
            if (oss != null) {
                oss.shutdown();
            }
        }

        // 文件上传成功之后将文件的url拼出来并返回
        String url = endpoint.split("//")[0] + "//" + bucketName + "." + endpoint.split("//")[1] + "/" + fileName;

        return url;

    }
}
